<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="培养方案" prop="trainingProgramId">
        <el-select v-model="form.trainingProgramId" placeholder="请选择培养方案" clearable style="width: 150px;">
          <el-option
              v-for="tm in trainingManagementList"
              :key="tm.id"
              :label="tm.name"
              :value="tm.id"
          />
        </el-select>
      </el-form-item>
      <!--年级-->
      <el-form-item label="年级" prop="gradeId">
        <el-select v-model="form.gradeId" placeholder="请选择年级" clearable style="width: 150px;">
          <el-option
              v-for="dict in grade"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程类型" prop="courseCharacter">
        <el-select v-model="queryParams.courseCharacter" placeholder="请选择课程类型" clearable style="width: 150px;">
          <el-option
              v-for="dict in type_of_course"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--开课学期-->
      <el-form-item label="开课学期" prop="term">
        <el-select v-model="queryParams.semester" placeholder="请选择开课学期" clearable style="width: 150px;">
          <el-option
              v-for="dict in semester"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程" prop="courseId">
        <el-select v-model="queryParams.courseId" placeholder="请选择课程" clearable style="width: 150px;">
          <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.courseName"
              :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8 status-button-row">
      <el-col :span="6">
        <el-button
            :type="activeStatus === '1' ? 'primary' : 'default'"
            @click="handleStatusClick('1')"
            class="status-btn"
        >
          待加入排课任务
        </el-button>
      </el-col>
      <el-col :span="6">
        <el-button
            :type="activeStatus === '2' ? 'primary' : 'default'"
            @click="handleStatusClick('2')"
            class="status-btn"
        >
          当前排课任务
        </el-button>
      </el-col>
      <el-col :span="6">
        <el-button
            :type="activeStatus === '3' ? 'primary' : 'default'"
            @click="handleStatusClick('3')"
            class="status-btn"
        >
          已完成分班任务
        </el-button>
      </el-col>
      <el-col :span="6">
        <el-button
            :type="activeStatus === 'all' ? 'primary' : 'default'"
            @click="handleStatusClick('all')"
            class="status-btn"
        >
          全部排课任务
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格：操作列合并+是否跨学期重点标注 -->
    <el-table v-loading="loading" :data="programPoursesList" @selection-change="handleSelectionChange" :span-method="objectSpanMethod">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程名称" align="center">
        <template #default="scope">
          {{ getCourseNameById(scope.row.courseId) }}
        </template>
      </el-table-column>
      <el-table-column label="学院名称" align="center">
        <template #default="scope">
          {{ getDeptNameByCourseId(scope.row.courseId) }}
        </template>
      </el-table-column>
      <el-table-column label="年级" align="center" prop="grade">
        <template #default="scope">
          <dict-tag :options="grade" :value="scope.row.grade"/>
        </template>
      </el-table-column>
      <el-table-column label="开课学期" align="center" prop="semester">
        <template #default="scope">
          <dict-tag :options="semester" :value="scope.row.semester" />
        </template>
      </el-table-column>
      <el-table-column label="培养方案名称" align="center">
        <template #default="scope">
          {{ getTrainingManagementName(scope.row.trainingProgramId) }}
        </template>
      </el-table-column>
      <el-table-column label="总学时" align="center" prop="totalHours" />
      <el-table-column label="学分" align="center" prop="credits" />
      <el-table-column label="授课方式" align="center" prop="teachingMethod">
        <template #default="scope">
          <dict-tag :options="teaching_method" :value="scope.row.teachingMethod" />
        </template>
      </el-table-column>
      <el-table-column label="考试方式" align="center" prop="examMethod">
        <template #default="scope">
          <dict-tag :options="method_examination" :value="scope.row.examMethod" />
        </template>
      </el-table-column>
      <el-table-column label="课程性质" align="center" prop="courseCharacter">
        <template #default="scope">
          <dict-tag :options="characteristics_of_the_course" :value="scope.row.courseCharacter" />
        </template>
      </el-table-column>
      <!-- 关键修改：是否跨学期列（自定义渲染+重点标注） -->
      <el-table-column label="是否跨学期" align="center" prop="isCrossSemester">
        <template #default="scope">
          <span :class="getCrossSemesterClass(scope.row.isCrossSemester)">
            {{ getCrossSemesterLabel(scope.row.isCrossSemester) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="开课学期数" align="center" prop="crossSemesterCount" />
      <el-table-column label="已完成学期数" align="center" prop="accomplishSemesterCount" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.statusNum)">
            {{ getStatusText(scope.row.statusNum) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280">
        <template #default="{ row, $index }">
          <el-button
              v-if="showArrangeButtonMap.get(getButtonKey(row)) === $index && [2, 3].includes(Number(row.statusNum))"
              @click="handleArrangeClass(row)"
              style="width: 100%;"
          >
            {{ Number(row.statusNum) === 3 ? '调整学生名单' : '开课编排班级' }}
          </el-button>
          <el-button
              type="primary"
              v-if="activeStatus === '1'"
              @click="handleAddTask(row)"
              style="width: 100%;"
          >
            添加排课任务
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="programPoursesRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="培养计划ID" prop="trainingProgramId">
          <el-select v-model="form.trainingProgramId" placeholder="请选择培养方案" required>
            <el-option
                v-for="tm in trainingManagementList"
                :key="tm.id"
                :label="tm.name"
                :value="tm.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择年级">
            <el-option
                v-for="dict in grade"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程类型" prop="courseCharacter">
          <el-select v-model="form.courseCharacter" placeholder="请选择课程类型">
            <el-option
                v-for="dict in type_of_course"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程ID" clearable>
            <el-option
                v-for="item in courseList"
                :key="item.id"
                :label="item.courseName"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开课学期" prop="semester">
          <el-select v-model="form.semester" placeholder="请选择开课学期" clearable>
            <el-option
                v-for="dict in semester"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否需要选课" prop="electiveSystem">
          <el-select v-model="form.electiveSystem" placeholder="请选择是否需要选课" clearable>
            <el-option
                v-for="dict in y_n"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总学时" prop="totalHours">
          <el-input v-model="form.totalHours" placeholder="请输入总学时" />
        </el-form-item>
        <el-form-item label="学分" prop="credits">
          <el-input v-model="form.credits" placeholder="请输入学分" />
        </el-form-item>
        <el-form-item label="授课方式" prop="teachingMethod">
          <el-select v-model="form.teachingMethod" placeholder="请选择授课方式">
            <el-option
                v-for="dict in teaching_method"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试方式" prop="examMethod">
          <el-select v-model="form.examMethod" placeholder="请选择考试方式">
            <el-option
                v-for="dict in method_examination"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否必修" prop="isRequired">
          <el-select v-model="form.isRequired" placeholder="请选择是否必修">
            <el-option
                v-for="dict in characteristics_of_the_course"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="记录创建时间" prop="createdAt">
          <el-date-picker clearable
                          v-model="form.createdAt"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择记录创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="记录更新时间" prop="updatedAt">
          <el-date-picker clearable
                          v-model="form.updatedAt"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择记录更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProgramPourses">
import {
  listProgramPourses,
  getProgramPourses,
  delProgramPourses,
  addProgramPourses,
  updateProgramPourses,
  listProgramPoursesOfstatus,
  updateStatusById
} from "@/api/trainingManagement/programPourses";
import {listCourse, getCourse} from "@/api/course/course";
import {loadAllParams} from "@/api/page";
import {listTrainingManagement} from "@/api/trainingManagement/trainingManagement";
import {useRouter} from 'vue-router';
import DictTag from "@/components/DictTag/index.vue";
import {ref, reactive, computed, onMounted, getCurrentInstance} from 'vue';
import { selectTrainingProgramCoursesListByCollegeIds,selectTrainingProgramCoursesListByCollegeIdswhereCourse } from "@/api/student/allList";

const {proxy} = getCurrentInstance();
const router = useRouter();

// 1. 字典数据
const {
  type_of_course,
  y_n,
  method_examination,
  teaching_method,
  compulsory,
  semester,
  grade,
  characteristics_of_the_course,
  teaching_task_status,
  spans_semesters
} = proxy.useDict(
    'type_of_course',
    'y_n',
    'method_examination',
    'teaching_method',
    'compulsory',
    'semester',
    'grade',
    'characteristics_of_the_course',
    'teaching_task_status',
    "spans_semesters"
);

// 2. 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10000,
  trainingProgramId: null,
  courseCharacter: null,
  courseId: null,
  electiveSystem: null,
  totalHours: null,
  credits: null,
  teachingMethod: null,
  examMethod: null,
  isRequired: null,
  grade: null,
  createdAt: null,
  updatedAt: null,
  isCrossSemester: null,
  crossSemesterCount: null,
  accomplishSemesterCount: null
});

// 3. 响应式数据
const programPoursesList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeStatus = ref('all');
const showArrangeButtonMap = ref(new Map());
const spanData = ref([]);

// 4. 表单数据
const data = reactive({
  form: {},
  rules: {
    trainingProgramId: [{required: true, message: "培养计划ID不能为空", trigger: "blur"}],
    courseId: [{required: true, message: "课程ID不能为空", trigger: "blur"}]
  }
});
const {form, rules} = toRefs(data);

// 5. 计算属性：字段映射
const courseNameMap = computed(() => {
  const map = new Map();
  courseList.value.forEach(course => map.set(course.id, course.courseName));
  return map;
});
const trainingNameMap = computed(() => {
  const map = new Map();
  trainingManagementList.value.forEach(tm => map.set(tm.id, tm.name));
  return map;
});
const courseDeptMap = computed(() => {
  const map = new Map();
  courseList.value.forEach(course => map.set(course.id, course.departmentId || '未知学院'));
  return map;
});

// 6. 基础方法：字段取值
const getCourseNameById = (courseId) => courseNameMap.value.get(courseId) || '未知课程';
const getDeptNameByCourseId = (courseId) => courseDeptMap.value.get(courseId) || '未知学院';
const getTrainingManagementName = (trainingProgramId) => {
  const tm = trainingManagementList.value.find(item => item.id === trainingProgramId);
  return tm ? tm.name : '未知培养方案';
};

// 7. 核心新增：是否跨学期标签获取（兼容空值和字典匹配）
const getCrossSemesterLabel = (value) => {
  // 处理空值/未定义，避免显示空白
  if (value === null || value === undefined || value === '') {
    return '未知';
  }
  // 统一转为字符串匹配（兼容数字1和字符串"1"）
  const dictItem = spans_semesters.value.find(item => String(item.value) === String(value));
  // 匹配不到时显示“未匹配+原始值”，便于排查字典配置问题
  return dictItem ? dictItem.label : `未匹配(${value})`;
};

// 8. 核心新增：是否跨学期高亮样式判断（仅键值1时重点标注）
const getCrossSemesterClass = (value) => {
  // 仅当值为1时（统一字符串判断，避免类型问题）
  return String(value) === '1' ? 'highlight-cross-semester' : '';
};

// 9. 核心辅助函数1：判断分组内字段是否一致
const checkFieldConsistency = (group, field) => {
  if (group.length <= 1) return true;
  const firstVal = group[0][field];
  return group.every(row => {
    const currVal = row[field];
    if ((firstVal == null || firstVal === "") && (currVal == null || currVal === "")) return true;
    return firstVal === currVal;
  });
};

// 10. 核心辅助函数2：生成操作按钮的Key
const getButtonKey = (row) => {
  const courseName = getCourseNameById(row.courseId) || "";
  const deptName = getDeptNameByCourseId(row.courseId) || "";
  const grade = (row.grade || 0).toString();
  const status = (row.statusNum || 0).toString();
  return `${courseName}-${deptName}-${grade}-${status}`;
};

// 11. 状态相关方法
const getStatusText = (status) => {
  if (!status && status !== 0) return '待加入排课任务';
  const item = teaching_task_status.value.find(i => String(i.value) === String(status));
  return item ? item.label : `未知状态(${status})`;
};
const getStatusTagType = (status) => {
  if (!status && status !== 0) return 'warning';
  switch (String(status)) {
    case "1": case "4": return "info";
    case "2": return "success";
    case "3": return "primary";
    default: return "danger";
  }
};

// 12. 数据加载：排序按四字段
async function fetchData(source = 'default', params = {}) {
  loading.value = true;
  try {
    let response;
    switch (source) {
      case 'collegeIds':
        response = await selectTrainingProgramCoursesListByCollegeIds(params);
        break;
      case 'collegeIdsWhereCourse':
        response = await selectTrainingProgramCoursesListByCollegeIdswhereCourse(params);
        break;
      case 'status':
        const safeStatusList = Array.isArray(params.statusList)
            ? params.statusList.map(s => Number(s)).filter(s => !isNaN(s) && Number.isInteger(s))
            : [];
        response = await listProgramPoursesOfstatus(safeStatusList, params.queryParams);
        break;
      default:
        response = await listProgramPourses(params);
    }

    let rows = (response.rows || []).map(item => ({
      ...item,
      statusNum: Number(item.status) || 0,
      status: item.status
    }));
    // 排序逻辑：课程名称 → 学院名称 → 年级 → 状态
    rows.sort((a, b) => {
      const courseNameA = getCourseNameById(a.courseId) || "";
      const courseNameB = getCourseNameById(b.courseId) || "";
      if (courseNameA !== courseNameB) return courseNameA.localeCompare(courseNameB);

      const deptNameA = getDeptNameByCourseId(a.courseId) || "";
      const deptNameB = getDeptNameByCourseId(b.courseId) || "";
      if (deptNameA !== deptNameB) return deptNameA.localeCompare(deptNameB);

      const gradeA = a.grade || 0;
      const gradeB = b.grade || 0;
      if (gradeA !== gradeB) return gradeA - gradeB;

      return (a.statusNum || 0) - (b.statusNum || 0);
    });

    spanData.value = prepareSpanData(rows);
    processArrangeButtonMap(rows);
    programPoursesList.value = rows;
    total.value = response.total || 0;
  } catch (error) {
    console.error("数据加载失败:", error);
    proxy.$modal.msgError("数据加载失败，请检查网络连接");
  } finally {
    loading.value = false;
  }
}

// 13. 核心方法1：生成合并规则（含操作列）
function prepareSpanData(data) {
  if (activeStatus.value === '1' || activeStatus.value === 'all') {
    return data.map(() => ({
      col1: {rowspan: 1, colspan: 1},
      col2: {rowspan: 1, colspan: 1},
      col3: {rowspan: 1, colspan: 1},
      col4: {rowspan: 1, colspan: 1},
      col6: {rowspan: 1, colspan: 1},
      col7: {rowspan: 1, colspan: 1},
      col8: {rowspan: 1, colspan: 1},
      col9: {rowspan: 1, colspan: 1},
      col10: {rowspan: 1, colspan: 1},
      col11: {rowspan: 1, colspan: 1},
      col12: {rowspan: 1, colspan: 1},
      col13: {rowspan: 1, colspan: 1},
      col14: {rowspan: 1, colspan: 1},
      col15: {rowspan: 1, colspan: 1} // 操作列不合并
    }));
  }

  const spanDataArr = new Array(data.length).fill(null);
  let currentPos = 0;
  while (currentPos < data.length) {
    const baseRow = data[currentPos];
    const groupKey = `${getCourseNameById(baseRow.courseId)}-${getDeptNameByCourseId(baseRow.courseId)}-${baseRow.grade || 0}-${baseRow.statusNum || 0}`;
    let groupEnd = currentPos;
    while (groupEnd < data.length) {
      const currRow = data[groupEnd];
      const currKey = `${getCourseNameById(currRow.courseId)}-${getDeptNameByCourseId(currRow.courseId)}-${currRow.grade || 0}-${currRow.statusNum || 0}`;
      if (currKey !== groupKey) break;
      groupEnd++;
    }

    const groupSize = groupEnd - currentPos;
    const currentGroup = data.slice(currentPos, groupEnd);
    const fieldConsistency = {
      semester: checkFieldConsistency(currentGroup, 'semester'),
      totalHours: checkFieldConsistency(currentGroup, 'totalHours'),
      credits: checkFieldConsistency(currentGroup, 'credits'),
      teachingMethod: checkFieldConsistency(currentGroup, 'teachingMethod'),
      examMethod: checkFieldConsistency(currentGroup, 'examMethod'),
      courseCharacter: checkFieldConsistency(currentGroup, 'courseCharacter'),
      isCrossSemester: checkFieldConsistency(currentGroup, 'isCrossSemester'),
      crossSemesterCount: checkFieldConsistency(currentGroup, 'crossSemesterCount'),
      accomplishSemesterCount: checkFieldConsistency(currentGroup, 'accomplishSemesterCount')
    };

    for (let i = currentPos; i < groupEnd; i++) {
      const isFirstRow = i === currentPos;
      spanDataArr[i] = {
        // 强制合并字段
        col1: isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0},
        col2: isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0},
        col3: isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0},
        col14: isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0},

        // 动态合并字段
        col4: fieldConsistency.semester ? (isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0}) : {rowspan: 1, colspan: 1},
        col6: fieldConsistency.totalHours ? (isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0}) : {rowspan: 1, colspan: 1},
        col7: fieldConsistency.credits ? (isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0}) : {rowspan: 1, colspan: 1},
        col8: fieldConsistency.teachingMethod ? (isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0}) : {rowspan: 1, colspan: 1},
        col9: fieldConsistency.examMethod ? (isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0}) : {rowspan: 1, colspan: 1},
        col10: fieldConsistency.courseCharacter ? (isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0}) : {rowspan: 1, colspan: 1},
        col11: fieldConsistency.isCrossSemester ? (isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0}) : {rowspan: 1, colspan: 1},
        col12: fieldConsistency.crossSemesterCount ? (isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0}) : {rowspan: 1, colspan: 1},
        col13: fieldConsistency.accomplishSemesterCount ? (isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0}) : {rowspan: 1, colspan: 1},

        // 操作列合并（与强制字段同步）
        col15: isFirstRow ? {rowspan: groupSize, colspan: 1} : {rowspan: 0, colspan: 0}
      };
    }
    currentPos = groupEnd;
  }
  return spanDataArr;
}

// 14. 核心方法2：表格合并应用
function objectSpanMethod({rowIndex, columnIndex}) {
  const info = spanData.value[rowIndex];
  if (!info) return {rowspan: 1, colspan: 1};

  switch (columnIndex) {
    case 1: return info.col1;
    case 2: return info.col2;
    case 3: return info.col3;
    case 4: return info.col4;
    case 6: return info.col6;
    case 7: return info.col7;
    case 8: return info.col8;
    case 9: return info.col9;
    case 10: return info.col10;
    case 11: return info.col11;
    case 12: return info.col12;
    case 13: return info.col13;
    case 14: return info.col14;
    case 15: return info.col15; // 操作列合并规则
    default: return {rowspan: 1, colspan: 1};
  }
}

// 15. 核心方法3：操作按钮映射
function processArrangeButtonMap(dataList) {
  const buttonMap = new Map();
  if (!['2', '3'].includes(activeStatus.value)) {
    showArrangeButtonMap.value = buttonMap;
    return;
  }

  let pos = 0;
  while (pos < dataList.length) {
    const row = dataList[pos];
    const key = getButtonKey(row);
    if (!buttonMap.has(key)) {
      buttonMap.set(key, pos);
    }
    const rowspan = spanData.value[pos]?.col1?.rowspan || 1;
    pos += rowspan;
  }
  showArrangeButtonMap.value = buttonMap;
}

// 16. 业务方法：状态切换、搜索等
function handleStatusClick(status) {
  activeStatus.value = status;
  queryParams.value.pageNum = 1;
  switch (status) {
    case '1':
      fetchData('collegeIds', {pageNum: 1, pageSize: queryParams.value.pageSize});
      break;
    case '2':
      fetchData('collegeIdsWhereCourse', {pageNum: 1, pageSize: queryParams.value.pageSize});
      break;
    case '3':
      fetchData('status', {statusList: [3], queryParams: {pageNum: 1, pageSize: queryParams.value.pageSize}});
      break;
    case 'all':
      fetchData('default', queryParams.value);
      break;
    default:
      programPoursesList.value = [];
      total.value = 0;
  }
}
async function handleAddTask(row) {
  try {
    await proxy.$modal.confirm('确定要将此课程添加到排课任务中吗？');
    await updateStatusById(row.id, 2);
    proxy.$modal.msgSuccess('已成功添加到排课任务');
    handleStatusClick(activeStatus.value);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('添加排课任务失败:', error);
      proxy.$modal.msgError('添加排课任务失败，请重试');
    }
  }
}
function handleQuery() {
  queryParams.value.pageNum = 1;
  handleStatusClick(activeStatus.value);
}
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value = {
    pageNum: 1,
    pageSize: 10000,
    trainingProgramId: null,
    courseCharacter: null,
    courseId: null,
    electiveSystem: null,
    totalHours: null,
    credits: null,
    teachingMethod: null,
    examMethod: null,
    isRequired: null,
    grade: null,
    createdAt: null,
    updatedAt: null,
    isCrossSemester: null,
    crossSemesterCount: null,
    accomplishSemesterCount: null
  };
  handleStatusClick(activeStatus.value);
}
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加培养计划课程明细";
}
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getProgramPourses(_id).then(res => {
    form.value = res.data;
    open.value = true;
    title.value = "修改培养计划课程明细";
  });
}
async function handleArrangeClass(row) {
  try {
    const courseId = row.courseId || "";
    const grade = (row.grade || 0).toString();
    const semester = (row.semester || 0).toString();
    const gradeNum = parseInt(grade);
    const semesterNum = parseInt(semester);

    const matchedRows = programPoursesList.value.filter(item =>
        item.courseId === courseId && (item.grade || 0) === gradeNum && (item.semester || 0) === semesterNum
    );
    const trainingProgramCoursesIds = matchedRows.map(item => item.id).filter(id => id);
    const trainingProgramIds = [...new Set(matchedRows.map(item => item.trainingProgramId))].filter(id => id);

    let numberClasses = null;
    let numberStudents = null;
    let isValid = true;
    if (matchedRows.length) {
      numberClasses = matchedRows[0].numberClasses;
      numberStudents = matchedRows[0].numberStudents;
      isValid = matchedRows.every(item =>
          areValuesConsistent(numberClasses, item.numberClasses) &&
          areValuesConsistent(numberStudents, item.numberStudents)
      );
    }
    if (!isValid) {
      proxy.$modal.msgError("选中的多行数据中，班级数量或学生数量不一致，请先统一数据");
      return;
    }

    if (trainingProgramIds.length) {
      router.push({
        path: '/arrange-class',
        query: {
          courseId, grade, semester, status: row.status,
          numberClasses: numberClasses || '',
          numberStudents: numberStudents || '',
          trainingProgramCoursesIds: trainingProgramCoursesIds.join(','),
          trainingProgramIds: trainingProgramIds.join(','),
          courseCharacter: row.courseCharacter || ''
        }
      });
    } else {
      proxy.$modal.msgWarn("未找到相关培养方案数据");
    }
  } catch (error) {
    console.error("编排班级失败:", error);
    proxy.$modal.msgError("加载数据失败，请重试");
  }
}
function cancel() {
  open.value = false;
  reset();
}
function reset() {
  form.value = {
    id: null,
    trainingProgramId: null,
    courseCharacter: null,
    courseId: null,
    electiveSystem: null,
    totalHours: null,
    credits: null,
    teachingMethod: null,
    examMethod: null,
    isRequired: null,
    semester: null,
    createdAt: null,
    updatedAt: null,
    isCrossSemester: null,
    crossSemesterCount: null,
    accomplishSemesterCount: null
  };
  proxy.resetForm("programPoursesRef");
}
function submitForm() {
  proxy.$refs["programPoursesRef"].validate(valid => {
    if (valid) {
      const func = form.value.id ? updateProgramPourses : addProgramPourses;
      func(form.value).then(() => {
        proxy.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功");
        open.value = false;
        handleStatusClick(activeStatus.value);
      });
    }
  });
}
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm(`是否确认删除培养计划课程明细编号为"${_ids}"的数据项？`).then(() => {
    delProgramPourses(_ids).then(() => {
      proxy.$modal.msgSuccess("删除成功");
      handleStatusClick(activeStatus.value);
    });
  });
}
function handleExport() {
  proxy.download('trainingManagement/programPourses/export', queryParams.value, `programPourses_${Date.now()}.xlsx`);
}

// 17. 辅助方法：值一致性判断
function areValuesConsistent(value1, value2) {
  if ((value1 == null || value1 === "") && (value2 == null || value2 === "")) return true;
  return value1 === value2;
}

// 18. 初始化加载
const courseList = ref([]);
const trainingManagementList = ref([]);
function getCourseList() {
  return new Promise(resolve => {
    if (courseList.value.length) {
      resolve();
      return;
    }
    listCourse(loadAllParams).then(res => {
      courseList.value = res.rows;
      resolve();
    });
  });
}
async function getTrainingManagementList() {
  if (trainingManagementList.value.length) return;
  try {
    const res = await listTrainingManagement({});
    trainingManagementList.value = res.rows;
  } catch (error) {
    console.error('获取培养方案列表失败:', error);
    proxy.$modal.msgError('培养方案加载失败');
  }
}
async function initData() {
  loading.value = true;
  try {
    await Promise.all([getCourseList(), getTrainingManagementList()]);
    handleStatusClick('all');
  } catch (error) {
    console.error("初始化失败:", error);
    proxy.$modal.msgError("数据加载失败");
  } finally {
    loading.value = false;
  }
}

// 19. 页面挂载
onMounted(() => {
  initData();
});
</script>

<style scoped>
/* 基础样式 */
.app-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.el-form-item {
  margin-bottom: 16px;
}
.mb8 {
  margin-bottom: 16px;
}

/* 状态按钮样式 */
.status-button-row {
  display: flex;
  align-items: center;
  width: 100%;
}
.status-btn {
  width: 100%;
  height: 60px;
  padding: 0 50px;
  font-size: 20px;
}

/* 表格样式 */
:deep(.el-table .cell) {
  display: flex !important;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

/* 标签样式 */
.el-tag {
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}
.el-tag--success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}
.el-tag--info {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}
.el-tag--primary {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}
.el-tag--warning {
  background-color: #fffbe6;
  border-color: #ffe88f;
  color: #faad14;
}

/* 关键新增：是否跨学期=是（键值1）的重点标注样式 */
.highlight-cross-semester {
  color: #f56c6c; /* 红色字体（突出警示） */
  font-weight: 700; /* 加粗 */
  padding: 2px 6px; /* 内边距，增强视觉区分 */
  border: 1px solid #f56c6c; /* 红色边框 */
  border-radius: 4px; /* 圆角 */
  background-color: rgba(245, 108, 108, 0.05); /* 浅红色背景 */
}

/* 按钮样式 */
.el-button {
  transition: all 0.3s ease;
}
.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式 */
@media (max-width: 1200px) {
  .el-form-item {
    width: 100%;
  }
  .el-select, .el-input {
    width: 100% !important;
  }
}
</style>